import { ref, watchEffect, defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'
import { useAsyncAxios } from '@/utils/asyncFuncStore'
import { useModalStore } from '@/stores/modalStore'
import type { ContentText, ErrorData, WorkArticle } from '@/types/loginType'
import { useWorkBenchStore } from '@/stores/workBenchStore'
import { storeToRefs } from 'pinia'

export default function () {
  // 识别路径
  const route = useRoute()
  const articleId = route.query.id as string

  // 标题元素
  const titleText = ref<HTMLTextAreaElement | null>(null)

  // 换图控制
  const mainImgUrl = ref<string>('')
  const inputFile = ref()
  const showMainImg = ref(false)

  //   获取上传图片的 URL
  function getTitleImgFile(e: HTMLInputElement) {
    const file = e.files
    if (file !== null) {
      const reader = new FileReader()
      reader.readAsDataURL(file[0])
      reader.onload = () => {
        const url = reader.result
        mainImgUrl.value = url as string
        showMainImg.value = true
      }
    }
  }

  // 上传的数据
  const formSet = ref<Set<HTMLInputElement>>(new Set())
  function collectData(e: HTMLInputElement) {
    formSet.value.add(e)
  }
  function getFormData() {
    const formData = new FormData()
    formSet.value.forEach((input) => {
      if (input.type === 'file' && input.files) {
        if (!!input.name && true) {
          formData.append(input.name, input.files[0])
        }
      } else {
        if (input.value.trim()) {
          formData.append(input.name, input.value)
        }
      }
    })
    return formData
  }

  // 获取动态变化的文章
  watchEffect(async () => {
    await getArticle()
  })

  // 获取指定文章
  async function getArticle() {
    const { getSaveArticle } = useAsyncAxios()
    const { changeData } = useModalStore()

    if (!!articleId && true) {
      const { status, data } = await getSaveArticle(articleId)
      console.log(data)

      if (status === 200) {
        const { title, mainImg, content } = data as WorkArticle
        const { assignImgData, assignTextData } = useWorkBenchStore()
        const { contentIndex } = storeToRefs(useWorkBenchStore())
        // 填充数据
        //
        console.log({ title, mainImg, content })

        if (mainImg) {
          mainImgUrl.value = mainImg
          showMainImg.value = true
        }
        if (titleText.value) {
          titleText.value.value = title
        }
        if (content.length !== 0) {
          content.forEach((item) => {
            if (item.name.startsWith('contentText')) {
              assignTextData({
                name: item.name,
                content: unescapeHtml((item as ContentText).content),
                type: defineAsyncComponent(() => import('@/components/workBench/typeText.vue'))
              })
            }
            if (item.name.startsWith('contentImg')) {
              assignImgData({
                ...item,
                type: defineAsyncComponent(() => import('@/components/workBench/typeImg.vue'))
              })
            }
          })
        } else {
          assignTextData({
            name: 'contentText' + contentIndex.value,
            content: '',
            type: defineAsyncComponent(() => import('@/components/workBench/typeText.vue'))
          })
        }
      } else {
        changeData({ status, data: data as ErrorData })
      }
    }
  }

  function unescapeHtml(html: string) {
    // 创建一个新的DOMParser对象
    const parser = new DOMParser()
    // 使用DOMParser解析包含转义字符的字符串
    const doc = parser.parseFromString(html, 'text/html')
    // 从解析结果中提取文本内容
    return doc.body.textContent || ''
  }

  return {
    articleId,
    titleText,
    mainImgUrl,
    inputFile,
    showMainImg,
    getTitleImgFile,
    formSet,
    collectData,
    getFormData
  }
}
